import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Input,
  Select,
  Space,
  Tag,
  Modal,
  Form,
  DatePicker,
  InputNumber,
  message,
  Popconfirm,
  Card
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  EyeOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import apiService from '../../services/apiService';
import moment from 'moment';

const { Option } = Select;
const { RangePicker } = DatePicker;

const CourseList = () => {
  const [courses, setCourses] = useState([]);
  const [teachers, setTeachers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingCourse, setEditingCourse] = useState(null);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const { user, isAdmin, isTeacher, isStudent } = useAuth();
  const navigate = useNavigate();
  const [form] = Form.useForm();

  useEffect(() => {
    loadCourses();
    if (isAdmin() || isTeacher()) {
      loadTeachers();
    }
  }, []);

  const loadCourses = async () => {
    try {
      setLoading(true);
      let data;
      if (isStudent()) {
        data = await apiService.getCoursesPublic();
      } else if (isTeacher()) {
        data = await apiService.getCoursesByTeacher(user.relatedId);
      } else {
        data = await apiService.getCourses();
      }
      setCourses(data);
    } catch (error) {
      message.error('加载课程列表失败');
      console.error('加载课程失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadTeachers = async () => {
    try {
      const data = await apiService.getTeachers();
      setTeachers(data);
    } catch (error) {
      console.error('加载教师列表失败:', error);
    }
  };

  const handleSearch = async () => {
    if (!searchKeyword.trim()) {
      loadCourses();
      return;
    }

    try {
      setLoading(true);
      const data = await apiService.searchCourses(searchKeyword);
      setCourses(data);
    } catch (error) {
      message.error('搜索失败: ' + (error.response?.data?.message || error.message));
      console.error('搜索课程失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleStatusFilter = async (status) => {
    setStatusFilter(status);
    if (!status) {
      loadCourses();
      return;
    }

    try {
      setLoading(true);
      const data = await apiService.getCoursesByStatus(status);
      setCourses(data);
    } catch (error) {
      message.error('筛选失败: ' + (error.response?.data?.message || error.message));
      console.error('筛选课程失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    setEditingCourse(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (course) => {
    setEditingCourse(course);
    form.setFieldsValue({
      ...course,
      teacherId: course.teacher?.id,
      timeRange: [
        moment(course.startTime),
        moment(course.endTime)
      ]
    });
    setModalVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      await apiService.deleteCourse(id);
      message.success('删除成功');
      loadCourses();
    } catch (error) {
      message.error('删除失败: ' + (error.response?.data?.message || error.message));
      console.error('删除课程失败:', error);
    }
  };

  const handleSubmit = async (values) => {
    try {
      const courseData = {
        ...values,
        startTime: values.timeRange[0].format(),
        endTime: values.timeRange[1].format()
      };
      delete courseData.timeRange;

      if (editingCourse) {
        await apiService.updateCourse(editingCourse.id, courseData);
        message.success('更新成功');
      } else {
        await apiService.createCourse(courseData);
        message.success('创建成功');
      }

      setModalVisible(false);
      loadCourses();
    } catch (error) {
      message.error((editingCourse ? '更新失败' : '创建失败') + ': ' + (error.response?.data?.message || error.message));
      console.error('提交课程失败:', error);
    }
  };

  const handleStatusChange = async (courseId, status) => {
    try {
      await apiService.updateCourseStatus(courseId, status);
      message.success('状态更新成功');
      loadCourses();
    } catch (error) {
      message.error('状态更新失败: ' + (error.response?.data?.message || error.message));
      console.error('更新课程状态失败:', error);
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'OPEN':
        return 'green';
      case 'FULL':
        return 'orange';
      case 'CLOSED':
        return 'red';
      default:
        return 'default';
    }
  };

  const getStatusText = (status) => {
    switch (status) {
      case 'OPEN':
        return '开放';
      case 'FULL':
        return '已满';
      case 'CLOSED':
        return '关闭';
      default:
        return status;
    }
  };

  const columns = [
    {
      title: '课程名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Button
          type="link"
          onClick={() => record && navigate(`/courses/${record.id}`)}
        >
          {text}
        </Button>
      )
    },
    {
      title: '课程代码',
      dataIndex: 'code',
      key: 'code'
    },
    {
      title: '教师',
      dataIndex: ['teacher', 'name'],
      key: 'teacher'
    },
    {
      title: '学分',
      dataIndex: 'credit',
      key: 'credit'
    },
    {
      title: '学时',
      dataIndex: 'hours',
      key: 'hours'
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      render: (text) => moment(text).format('YYYY-MM-DD HH:mm')
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      render: (text) => moment(text).format('YYYY-MM-DD HH:mm')
    },
    {
      title: '地点',
      dataIndex: 'location',
      key: 'location'
    },
    {
      title: '最大人数',
      dataIndex: 'maxStudents',
      key: 'maxStudents'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status, record) => {
        if (isAdmin() || isTeacher()) {
          return (
            <Select
              value={status}
              style={{ width: 80 }}
              onChange={(value) => record && handleStatusChange(record.id, value)}
            >
              <Option value="OPEN">
                <Tag color="green">开放</Tag>
              </Option>
              <Option value="FULL">
                <Tag color="orange">已满</Tag>
              </Option>
              <Option value="CLOSED">
                <Tag color="red">关闭</Tag>
              </Option>
            </Select>
          );
        }
        return (
          <Tag color={getStatusColor(status)}>
            {getStatusText(status)}
          </Tag>
        );
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => record && navigate(`/courses/${record.id}`)}
          >
            查看
          </Button>
          {(isAdmin() || isTeacher()) && (
            <>
              <Button
                type="link"
                icon={<EditOutlined />}
                onClick={() => record && handleEdit(record)}
              >
                编辑
              </Button>
              {isAdmin() && (
                <Popconfirm
                  title="确定要删除这门课程吗？"
                  onConfirm={() => record && handleDelete(record.id)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button
                    type="link"
                    danger
                    icon={<DeleteOutlined />}
                  >
                    删除
                  </Button>
                </Popconfirm>
              )}
            </>
          )}
        </Space>
      )
    }
  ];

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Input
              placeholder="搜索课程名称或描述"
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              onPressEnter={handleSearch}
              style={{ width: 300 }}
            />
            <Button
              type="primary"
              icon={<SearchOutlined />}
              onClick={handleSearch}
            >
              搜索
            </Button>
            <Select
              placeholder="筛选状态"
              value={statusFilter}
              onChange={handleStatusFilter}
              style={{ width: 120 }}
              allowClear
            >
              <Option value="OPEN">开放</Option>
              <Option value="FULL">已满</Option>
              <Option value="CLOSED">关闭</Option>
            </Select>
            {(isAdmin() || isTeacher()) && (
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleCreate}
              >
                新建课程
              </Button>
            )}
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={courses}
          rowKey="id"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`
          }}
        />
      </Card>

      <Modal
        title={editingCourse ? '编辑课程' : '新建课程'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="name"
            label="课程名称"
            rules={[{ required: true, message: '请输入课程名称' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="code"
            label="课程代码"
            rules={[{ required: true, message: '请输入课程代码' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="description"
            label="课程描述"
          >
            <Input.TextArea rows={3} />
          </Form.Item>

          <Form.Item
            name="teacherId"
            label="授课教师"
            rules={[{ required: true, message: '请选择授课教师' }]}
          >
            <Select placeholder="选择教师">
              {teachers.map(teacher => (
                <Option key={teacher.id} value={teacher.id}>
                  {teacher.name} - {teacher.department}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Space>
            <Form.Item
              name="credit"
              label="学分"
              rules={[{ required: true, message: '请输入学分' }]}
            >
              <InputNumber min={1} max={10} />
            </Form.Item>

            <Form.Item
              name="hours"
              label="学时"
              rules={[{ required: true, message: '请输入学时' }]}
            >
              <InputNumber min={1} max={200} />
            </Form.Item>

            <Form.Item
              name="maxStudents"
              label="最大人数"
              rules={[{ required: true, message: '请输入最大人数' }]}
            >
              <InputNumber min={1} max={500} />
            </Form.Item>
          </Space>

          <Form.Item
            name="timeRange"
            label="上课时间"
            rules={[{ required: true, message: '请选择上课时间' }]}
          >
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="location"
            label="上课地点"
            rules={[{ required: true, message: '请输入上课地点' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingCourse ? '更新' : '创建'}
              </Button>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CourseList;